﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;

namespace testreportmanager
{
    public partial class Upload : System.Web.UI.Page
    {
        private static string filespath;
        public string Filespath
        {
            get { return filespath; }            
        }

        private static string metadatapath;
        public string Metadatapath
        {
            get { return metadatapath; }
        }

        private static string featureEdit;
        public string FeatureEdit
        {
            get { return featureEdit; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {           
            filespath = Server.MapPath("files.xml");
            metadatapath = Server.MapPath("metadata.xml");
            GridView1.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Boolean fileOK = false;
           
            String path = Server.MapPath("~/data/");
            if (fUpload.HasFile)
            {
                String fileExtension =
                    System.IO.Path.GetExtension(fUpload.FileName).ToLower();
                String[] allowedExtensions = { ".trx" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }
            }

            if (fileOK)
            {
                DirectoryInfo diFiles = new DirectoryInfo(Server.MapPath("~/data/"));
                FileInfo[] files = diFiles.GetFiles("*.trx");
                bool filePresent = false;
                 //check if the file already exist
                foreach (FileInfo f in files)
                {
                    if (fUpload.FileName == f.Name) filePresent = true;
                }

                if (!filePresent)
                {
                    fUpload.PostedFile.SaveAs(path
                        + fUpload.FileName);

                    Label1.Text = "*File uploaded!";
                    Label1.ForeColor = System.Drawing.Color.Green;
                    ProcessTrx(path + fUpload.FileName);

                    Reports rep = new Reports();
                    rep.InsertResult(txtname.Text, fUpload.FileName, featurelst.SelectedItem.Text, buildlst.SelectedItem.Text);
                }
                else
                {
                    Label1.Text = "*File already exist.";
                    Label1.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                Label1.Text = "*Cannot accept files of this type.";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
            GridView1.DataBind();
        }

        private string ProcessTrx(string tempXml)
        { 
            XmlDocument doc = new XmlDocument();
            doc.Load(tempXml);
            XmlElement root = doc.DocumentElement;
            root.Attributes.RemoveAll();
            doc.Save(tempXml);

            string file = File.ReadAllText(tempXml);
            if (file.Contains("xmlns=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2006\""))
            {
                file = file.Replace("xmlns=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2006\"", "");
            }
            else if (file.Contains("xmlns=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\""))
            {
                file = file.Replace("xmlns=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"", "");
            }
            File.WriteAllText(tempXml, file);

            return tempXml;
        }

        protected void lbAddFeature_Click(object sender, EventArgs e)
        {
            tFeature.Visible = true;
            bFeatureSave.Visible = true;
            btnFeatureCancel.Visible = true;
        }

        protected void lbAddBuild_Click(object sender, EventArgs e)
        {
            tBuild.Visible = true;
            bBuildSave.Visible = true;
            btnBuildCancel.Visible = true;
        }

        protected void bFeatureSave_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(metadatapath);

            XmlDocumentFragment xmlDocFragment = doc.CreateDocumentFragment();
            xmlDocFragment.InnerXml = String.Format("<feature name=\"{0}\"/>", tFeature.Text);

            XmlNode aNode = doc.DocumentElement.FirstChild;
            aNode.InsertAfter(xmlDocFragment, aNode.LastChild);

            doc.Save(metadatapath);
            featurelst.DataBind();
            tFeature.Visible = false;
            bFeatureSave.Visible = false;
            btnFeatureCancel.Visible = false;
        }

        protected void bBuildSave_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(metadatapath);

            XmlDocumentFragment xmlDocFragment = doc.CreateDocumentFragment();
            xmlDocFragment.InnerXml = String.Format("<build name=\"{0}\"/>", tBuild.Text);

            XmlNode aNode = doc.DocumentElement.LastChild;
            aNode.InsertAfter(xmlDocFragment, aNode.LastChild);

            doc.Save(metadatapath);
            buildlst.DataBind();
            tBuild.Visible = false;
            bBuildSave.Visible = false;
            btnBuildCancel.Visible = false;
        }

        protected void GridView1_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string filename = (String)GridView1.DataKeys[e.RowIndex].Value;

            Reports rep = new Reports();
            rep.DeleteReport(filename);
            // // now delete the actual file
            DirectoryInfo diFiles = new DirectoryInfo(Server.MapPath("~/data/"));
            FileInfo[] files = diFiles.GetFiles("*.trx");

            //check if the file already exist
            foreach (FileInfo f in files)
            {
                if (filename == f.Name)
                {
                    f.Delete();
                }
            }
        }

        protected void GridView1_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            e.ExceptionHandled = true;
            GridView1.DataBind();
        }

        protected void btnFeatureCancel_Click(object sender, EventArgs e)
        {
            tFeature.Visible = false;
            bFeatureSave.Visible = false;
            btnFeatureCancel.Visible = false;
        }

        protected void btnBuildCancel_Click(object sender, EventArgs e)
        {
            tBuild.Visible = false;
            bBuildSave.Visible = false;
            btnBuildCancel.Visible = false;
        }

        //protected void GridView1_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
        //{
        //    GridViewRow row = GridView1.Rows[e.RowIndex];
        //    e.Cancel = false;
        //    string filename = (String)GridView1.DataKeys[e.RowIndex].Value;            
        //    string feature = ((DropDownList)(row.Cells[1].Controls[1])).Text;
        //    string build = ((DropDownList)(row.Cells[2].Controls[1])).Text;

        //    Reports rep = new Reports();
        //    rep.UpdateReport(filename, feature, build);
        //}        

        //protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        //{
        //    e.ExceptionHandled = true;
        //    GridView1.DataBind();
        //}        
        
    }

    public class Reports
    {
        XmlDocument xmlDoc;
        Upload a = new Upload();

        public Reports()
        {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(a.Filespath);
        }

        public void InsertResult(string reportname, string filename, string feature, string build)
        {
            XmlElement fileElem = xmlDoc.CreateElement("file");
            fileElem.Attributes.Append(XmlAttribute("name", reportname));
            fileElem.Attributes.Append(XmlAttribute("fname", filename));
            fileElem.Attributes.Append(XmlAttribute("feature", feature));
            fileElem.Attributes.Append(XmlAttribute("build", build));
            xmlDoc.DocumentElement.AppendChild(fileElem);
            xmlDoc.Save(a.Filespath);
        }

        public void DeleteReport(string filename)
        {
            XmlNode r = xmlDoc.SelectSingleNode(String.Format("/folder/file[@name='{0}']", filename));
            r.ParentNode.RemoveChild(r);
            xmlDoc.Save(a.Filespath);
        }

        public void UpdateReport(string filename, string feature, string build)
        {
            XmlNode r = xmlDoc.SelectSingleNode(String.Format("/folder/file[@name='{0}']", filename));
            r.Attributes["feature"].Value = feature;
            r.Attributes["build"].Value = build;
            xmlDoc.Save(a.Filespath);
        }

        private XmlAttribute XmlAttribute(string attributeName,
                                          string attributeValue)
        {
            XmlAttribute xmlAttrib =
                xmlDoc.CreateAttribute(attributeName);
            xmlAttrib.Value = FilterXMLString(attributeValue);
            return xmlAttrib;
        }

        private string FilterXMLString(string inputString)
        {
            string returnString = inputString;
            if (inputString.IndexOf("&") > 0)
            {
                returnString = inputString.Replace("&", "&");
            }
            if (inputString.IndexOf("'") > 0)
            {
                returnString = inputString.Replace("'", "&apos;");
            }
            return returnString;
        }
    }

    //public class FileSystemInfoLister
    //{

    //    XmlDocument xmlDoc;

    //    public FileSystemInfoLister()
    //    {
    //        xmlDoc = new XmlDocument();
    //    }

    //    public XmlDocument GetFileSystemInfoList(string StartFolder)
    //    {

    //        try
    //        {
    //            XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0",
    //                                                            "", "yes");
    //            xmlDoc.PrependChild(xmlDec);
    //            XmlElement nodeElem = XmlElement("folder",
    //                     new DirectoryInfo(StartFolder).Name);
    //            xmlDoc.AppendChild(AddElements(nodeElem, StartFolder));
    //        }
    //        catch (Exception ex)
    //        {
    //            xmlDoc.AppendChild(XmlElement("error", ex.Message));
    //            return xmlDoc;
    //        }
    //        return xmlDoc;
    //    }


    //    private XmlElement AddElements(XmlElement startNode, string Folder)
    //    {
    //        try
    //        {
    //            DirectoryInfo dir = new DirectoryInfo(Folder);
    //            DirectoryInfo[] subDirs = dir.GetDirectories();
    //            FileInfo[] files = dir.GetFiles();
    //            foreach (FileInfo fi in files)
    //            {
    //                XmlElement fileElem = XmlElement("file", fi.Name);
    //                fileElem.Attributes.Append(XmlAttribute("Extension",
    //                                                         fi.Extension));
    //                fileElem.Attributes.Append(XmlAttribute("Feature", "Devportal"));
    //                fileElem.Attributes.Append(XmlAttribute("Archive",
    //                 ((fi.Attributes & FileAttributes.Archive) != 0)
    //                                                     ? "Y" : "N"));
    //                fileElem.Attributes.Append(XmlAttribute("System",
    //                 ((fi.Attributes & FileAttributes.System) != 0)
    //                                                     ? "Y" : "N"));
    //                fileElem.Attributes.Append(XmlAttribute("ReadOnly",
    //                 ((fi.Attributes & FileAttributes.ReadOnly) != 0)
    //                                                      ? "Y" : "N"));
    //                startNode.AppendChild(fileElem);
    //            }
    //            foreach (DirectoryInfo sd in subDirs)
    //            {
    //                XmlElement folderElem = XmlElement("folder", sd.Name);
    //                folderElem.Attributes.Append(XmlAttribute("Hidden",
    //                  ((sd.Attributes & FileAttributes.Hidden) != 0)
    //                                                     ? "Y" : "N"));
    //                folderElem.Attributes.Append(XmlAttribute("System",
    //                  ((sd.Attributes & FileAttributes.System) != 0)
    //                                                     ? "Y" : "N"));
    //                folderElem.Attributes.Append(XmlAttribute("ReadOnly",
    //                  ((sd.Attributes & FileAttributes.ReadOnly) != 0)
    //                                                     ? "Y" : "N"));
    //                startNode.AppendChild(AddElements(folderElem,
    //                                                   sd.FullName));
    //            }
    //            return startNode;
    //        }
    //        catch (Exception ex)
    //        {
    //            return XmlElement("error", ex.Message);
    //        }
    //    }
    //    private XmlAttribute XmlAttribute(string attributeName,
    //                                      string attributeValue)
    //    {
    //        XmlAttribute xmlAttrib =
    //            xmlDoc.CreateAttribute(attributeName);
    //        xmlAttrib.Value = FilterXMLString(attributeValue);
    //        return xmlAttrib;
    //    }
    //    private XmlElement XmlElement(string elementName,
    //                                   string elementValue)
    //    {
    //        XmlElement xmlElement = xmlDoc.CreateElement(elementName);
    //        xmlElement.Attributes.Append(XmlAttribute("name",
    //                                  FilterXMLString(elementValue)));
    //        return xmlElement;
    //    }
    //    private string FilterXMLString(string inputString)
    //    {
    //        string returnString = inputString;
    //        if (inputString.IndexOf("&") > 0)
    //        {
    //            returnString = inputString.Replace("&", "&");
    //        }
    //        if (inputString.IndexOf("'") > 0)
    //        {
    //            returnString = inputString.Replace("'", "&apos;");
    //        }
    //        return returnString;
    //    }
    //}    

}